#include	"Categorie.h" 
#include <stdio.h>

Categorie::Categorie(int id, string nom){
	this->id = id;
	this->nom = nom;
	this->articles = new map<int,Article*>();
	this->articles_it = this->articles->begin();
}

Categorie::~Categorie(){
	delete this->articles;
}

int Categorie::creerArticle(string nom){
	int id = this->articles->size();
	while(this->getArticle(id)!=NULL){ //verifie que l'id n'existe pas
		id++;
	}
	Article * c = new Article(id,nom);
	articles->insert(pair<int,Article*>(id,c));
	this->articles_it = this->articles->begin(); //reinitialisation de l'iterateur
	return id;
}

void Categorie::supprimerArticle(int id){
	this->articles_it = this->articles->find(id);
	if(this->articles_it != this->articles->end()){
		this->articles->erase(id); //suppression de la reference
	}

	//delete this->getArticle(id); //liberation de la memoire
	articles->erase(id); //suppression de la reference
	this->articles_it = this->articles->begin(); //reinitialisation de l'iterateur
	return;
}


int Categorie::getId(){
	return this->id;
}

void Categorie::setNom(string nom){
	this->nom = nom;
}

string Categorie::getNom(){
	return this->nom;
}


void Categorie::majIterateurs(){
	this->articles_it = this->articles->begin();
}

Article* Categorie::getArticle(int id){
	if(this->articles->empty()){
		cout<<"< vide >"<<endl;
		return NULL;
	}
	if(id < 0){ //parcours par iterateur
		Article* c = (*articles_it).second;
		articles_it++;
		return c;
	}
	else{ //retour normal
		map<int,Article*>::iterator it = this->articles->find(id);
		if(it==this->articles->end()){
			return NULL;
		}
		else{
			return it->second;
		}
	}
}

int Categorie::getArticleId(string nom){
	this->majIterateurs();
	int id = -1;
	for(this->articles_it = this->articles->begin();this->articles_it!=this->articles->end();this->articles_it++){
		Article * x = this->articles_it->second;
		if(x->getNom() == nom)
			return x->getId();
	}
	return id;
}

string Categorie::toString(){
	string s = "";
	for(this->articles_it = this->articles->begin();this->articles_it!=this->articles->end();this->articles_it++){
		Article* c = this->articles_it->second;
		int id = c->getId();
		string nom = c->getNom();
		char ch[10];
		sprintf(ch,"%i",id);
		string result = ch;
		s+=" "+result+" : ";
		s+=nom+" \n";
	}
	if(s=="")
		s=" <vide>";
	s=this->nom + " :\n----------\n"+s;
	this->majIterateurs();
	return s;
}
